package de.carcophan.jimdb.jsf.security;

import de.carcophan.jimdb.ejb.entites.User;
import de.carcophan.jimdb.ejb.entites.service.AccessLogFacade;
import de.carcophan.jimdb.ejb.entites.service.UserFacade;
import de.carcophan.jimdb.jsf.mb.AbstractController;
import de.carcophan.jimdb.jsf.mb.util.JsfUtil;
import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Named
@SessionScoped
public class LoginController extends AbstractController implements Serializable {

    private String name;
    @EJB
    private AccessLogFacade accessLogFacade;
    @EJB
    private UserFacade userFacade;

    @PostConstruct
    private void getAccessData() {
        final HttpServletRequest request = (HttpServletRequest) getFacesContext().getExternalContext().getRequest();

        String userAgent = request.getHeader("user-agent");
        AccessLog accessLog = new AccessLog();
        accessLog.setUserAgent(userAgent);
        final Date date = new Date();
        accessLog.setHitDate(date);
        accessLog.setClientAddr(request.getRemoteAddr());
        accessLog.setHitTime(date);
        accessLogFacade.create(accessLog);

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    private String password;

    public String login() throws Exception {
        final FacesContext facesContext = getFacesContext();
        try {
            ((HttpServletRequest) facesContext.getExternalContext().getRequest()).login(name, password);
            User user = userFacade.findByLoginId(name);
            if (user.getLocked()){
                ((HttpSession) getFacesContext().getExternalContext().getSession(false)).invalidate();
                throw new ServletException("user locked!");
            }
        } catch (ServletException ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
            JsfUtil.addErrorMessage("Invalid user credentials");
            return null;
        }

        Application app = facesContext.getApplication();
        ViewHandler viewHandler = app.getViewHandler();
        UIViewRoot view = viewHandler.createView(facesContext, "/secured/index.xhtml");
        facesContext.setViewRoot(view);
        facesContext.renderResponse();

        viewHandler.renderView(facesContext, view);
        facesContext.responseComplete();

        return null;
    }

    /** Creates a new instance of LoginController */
    public LoginController() {
    }

    public String register() {
        if (getAuthenticatedUser() == null) {
            Logger.getLogger(LoginController.class.getName()).log(Level.INFO, "forwarding to Registration Form");
            return "Create";
        } else {
            return null;
        }
    }
}
